/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 StdRoundRobinCoordinator.cpp. Created on: 29.09.2009 14:36:25 
 */

#include "smartobjects/network/StdRoundRobinCoordinator.hpp"

namespace smartobjects {

const std::string StdRoundRobinCoordinator::COORDINATOR_NAME = "StdRoundRobinCoordinator";

StdRoundRobinCoordinator::StdRoundRobinCoordinator() {
}

StdRoundRobinCoordinator::~StdRoundRobinCoordinator() {
}

const std::string& StdRoundRobinCoordinator::getName() {
	return StdRoundRobinCoordinator::COORDINATOR_NAME;
}

void StdRoundRobinCoordinator::insertHandler(IManagedConnection* poManagedConnection, ConnectionHandler* poConnectionHandler) {
	boost::unique_lock<boost::recursive_mutex> oLock( m_mxCoordinator );
	StdFailOverCoordinator::insertHandler( poManagedConnection, poConnectionHandler );
	if(poManagedConnection->getCoordinatorContext() == NULL) {
		poManagedConnection->setCoordinatorContext(new Context());
	}
	else
		poManagedConnection->getCoordinatorContext()->reset();

}

ConnectionHandler* StdRoundRobinCoordinator::getConnectionHandlerToSend ( IManagedConnection* poConnection ) {
	boost::unique_lock<boost::recursive_mutex> oLock( m_mxCoordinator );
	Context* poContext = dynamic_cast<Context*> (poConnection->getCoordinatorContext());
	if(poContext == NULL) {
		throw SystemException("Internal error: Unable to found StdRoundRobin::Context in the managed connection");
	}
	ConnectionsMap::iterator itCon = m_mConnections.find(poConnection);
	if(itCon!=m_mConnections.end()) {
		Handlers& aHandlers = itCon->second;
		unsigned int nIdxHandler = poContext->updateRoundRobinCounter( aHandlers.size() );
		Handlers::const_iterator itHandler = aHandlers.begin();
		for(unsigned int nIdx = 0; nIdx < nIdxHandler && itHandler != aHandlers.end(); nIdx ++, itHandler++);
		ConnectionHandler* poHandler = *itHandler;
		poHandler->addRef();
		return poHandler;
	}
	else
		throw IOException("Unable to found any available connections to send!");
}

}
